package com.xtm.exercise.base.B14spring.initStart.startupComplete;

import com.xtm.exercise.base.B14spring.initStart.startupIncomplete.StaticBlockDemo;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/*
  如何在 Spring Boot 启动的时候运行一些特定的代码？

    服务启动成功，则执行此方法
        实现接口L:  implements ApplicationListener<ApplicationReadyEvent>

    spring boot中支持的事件类型如下：
        ApplicationFailedEvent：该事件为spring boot启动失败时的操作
        ApplicationPreparedEvent：上下文context准备时触发
        ApplicationReadyEvent：上下文已经准备完毕的时候触发
        ApplicationStartedEvent：spring boot 启动监听类
        SpringApplicationEvent：获取SpringApplication
        ApplicationEnvironmentPreparedEvent：环境事先准备

  */
@Component
public class InitSuccessDemo implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {

        System.out.println("服务启动成功，开始执行业务");

        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        //解决userService一直为空
        StaticBlockDemo staticDemo = applicationContext.getBean(StaticBlockDemo.class);

        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("spring.application.name");
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

    }


}
